<!--
 * @Description: 开通债权证明
 * @Author gong
 * @create 2024/9/5 15:02
 -->
<!--setup-->
<script setup>
import { onMounted, getCurrentInstance, ref } from 'vue'
import { BaseFormItem, BaseForm } from '@shared/base/base-form'
import Editor from '@shared/base/editor' // 富文本编辑器
import BaseUpload from '@/components/base-upload/index.vue'
import SvgIcon from '@/components/svg-icon/index.vue' // 文件上传
import { to } from 'sf-utils2'
import cfDebtTransferAgreementApi from '@/api/modules/cf-debt-transfer-agreement' // api接口
import { ElMessage } from 'element-plus'
import { $enums } from '@/utils/enums'

const { proxy } = getCurrentInstance()
const props = defineProps({
  // 债转证明是否开启过 true: 开过  false: 未开过
  editDebtTraAgrFlag: {
    type: Boolean,
    default: () => false
  },
  // 项目id
  prjId: {
    type: String,
    default: () => ''
  }
})
const emit = defineEmits([])

/* 状态 */
const formData = ref({})
const baseFormRef = ref() // base-form 实例
const uploadRef = ref(null) // 债务人列表实例

/* 方法 */
/**
 * 初始化数据
 */
const init = async () => {
  const [res, err] = await to(cfDebtTransferAgreementApi.getDebtTraAgrDetail({ prjId: props.prjId }))
  if (err || res?.code !== 200) return ElMessage.error(res?.message || String(err))
  formData.value = {
    ...res.data,
    proveType: '10' // 类型
  }
  // 如果存在债务人列表文件
  formData.value.file = [formData.value.cfFileInfoResp].filter(Boolean) // 债务人列表文件
  console.log('121212', formData.value)
}

/**
 * 下载模板
 */
const onDownloadTemplate = async () => {
  const [res, err] = await to(cfDebtTransferAgreementApi.debtTraAgrDownLoad('债转证明协议人员列表模板.xlsx'))
  if (err || res?.code !== 200) return ElMessage.error(res?.message || String(err))
  ElMessage.success('下载模板成功！')
}

/**
 * 改变文件状态
 * @param file
 * @param fileList
 */
const onFileChange = (file, fileList) => {
  // 重新赋值
  formData.value.file = fileList
}

/**
 * 校验并返回数据
 */
const onSave = async () => {
  const valid = await baseFormRef.value.validate()
  if (valid) {
    const params = {
      ...formData.value,
      prjId: props.prjId // 项目id
    }
    // 处理上传文件
    if (params.file && params.file.length) {
      params.fileInfoReq = params.file[0]?.file
      delete params.file
    }
    // 删除多余字段
    if (params.cfFileInfoResp) delete params.cfFileInfoResp

    const apiObj = {
      false: () => cfDebtTransferAgreementApi.cfDebtTransferAgreement(params),
      true: () => cfDebtTransferAgreementApi.updateCfDebtTraAgr(params)
    }
    const [res, err] = await to(apiObj[props.editDebtTraAgrFlag]?.())
    if (err || res?.code !== 200) {
      ElMessage.error(res?.message || String(err))
      return false
    }
    return res
  }
}

/* 计算 */

/* 监听 */

/* 周期 */
onMounted(() => {
  init()
})

/* 暴露 */
defineExpose({
  $: proxy.$,
  onSave
})
</script>

<!--render-->
<template>
  <BaseForm
    ref="baseFormRef"
    v-model="formData"
    label-position="top"
  >
    <BaseFormItem
      label="类型"
      prop="proveType"
      type="select"
      dict="debtTraAgrNoticeType"
      disabled
      :col="24"
    />
    <BaseFormItem
      label="标题"
      prop="title"
      type="input"
      required
      maxlength="200"
      :component-attrs="{ showWordLimit: false }"
      :col="24"
    />
    <BaseFormItem
      label="内容"
      prop="content"
      type="default"
      required
      :col="24"
    >
      <Editor
        v-model="formData.content"
        height="400px"
      />
    </BaseFormItem>
    <BaseFormItem
      label="债权人列表"
      prop="assetType"
      type="default"
      :col="24"
    >
      <template #label>
        <div class="mb-16px flex">
          <div class="mr-16px">
            债务人列表
          </div>
          <button
            class="flex items-center gap-1 text-primary"
            @click="onDownloadTemplate"
          >
            <SvgIcon
              svg="upload/download"
              size="14px"
            />
            下载模板
          </button>
        </div>
      </template>
      <template #default>
        <BaseUpload
          ref="uploadRef"
          v-model:file-list="formData.file"
          :data="{ businessType: '20' }"
          class="w-full"
          template="import"
          :drag="true"
          accept=".xls,.xlsx"
          :file-size="50"
          :limit="1"
          :exceed-replace="true"
          :module="$enums.pathModule.AGREEMENT"
          placeholder="仅支持扩展名：.xls .xlsx，文件上传大小限制50M"
          :on-change="onFileChange"
        />
      </template>
    </BaseFormItem>
  </BaseForm>
</template>

<!--style-->
<style scoped lang="less"></style>
